﻿using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace TestConfidenceReport
{
    public partial class FrmMain : Form
    {
        private TfsTeamProjectCollection _tfs;
        private WorkItemStore _teamWorkItemStore;
        private ITestManagementTeamProject _teamProject;

        private delegate void Execute();

        int flag1 = 0, flag2 = 0, flag3 = 0, flag4 = 0, flag5 = 0, flag6 = 0;
        string tfsQueryRootFolder = "My Queries";

        public FrmMain()
        {
            InitializeComponent();
            dtpCompleteStart.Value = DateTime.Today;
            dtpCompleteEnd.Value = DateTime.Today;
            cmbRunType.SelectedIndex = 0;
        }

        private void btnTeamProject_Click(object sender, EventArgs e)
        {
            //Displaying the Team Project selection dialog to select the desired team project.
            TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
            tpp.ShowDialog();

            //Following actions will be executed only if a team project is selected in the the opened dialog.
            if (tpp.SelectedTeamProjectCollection != null)
            {
                this._tfs = tpp.SelectedTeamProjectCollection;
                this._teamWorkItemStore = _tfs.GetService<WorkItemStore>();
                ITestManagementService test_service = (ITestManagementService)_tfs.GetService(typeof(ITestManagementService));
                this._teamProject = test_service.GetTeamProject(tpp.SelectedProjects[0].Name);

                //Populating the text field Team Project name (txtTeamProject) with the name of the selected team project.
                txtTeamProject.Text = tpp.SelectedProjects[0].Name;
                flag1 = 1;
            }
        }
        private void btnFolderBrowse_Click(object sender, EventArgs e)
        {
            folderBrowserDialog.ShowDialog();
            txtSaveFolder.Text = folderBrowserDialog.SelectedPath;
            if (txtSaveFolder.Text != null || txtSaveFolder.Text != "")
            {
                flag4 = 1;
            }
        }

        private void cbApplyDateFilter_CheckedChanged(object sender, EventArgs e)
        {
            if (cbApplyDateFilter.Checked)
            {
                dtpCompleteStart.Enabled = true;
                dtpCompleteEnd.Enabled = true;
            }
            else
            {
                dtpCompleteStart.Enabled = false;
                dtpCompleteEnd.Enabled = false;
            }
        }

        private List<WorkItemNode> GetWorkItems(string rootFolder, string tfsQuery)
        {
            QueryHierarchy queryRoot = _teamWorkItemStore.Projects[_teamProject.TeamProjectName].QueryHierarchy;
            QueryFolder queryFolder = (QueryFolder)queryRoot[rootFolder];
            QueryDefinition queryDef = (QueryDefinition)queryFolder[tfsQuery];
            Query query = new Query(_teamWorkItemStore, queryDef.QueryText);

            // get the link types
            var linkTypes = new List<WorkItemLinkType>(_teamWorkItemStore.WorkItemLinkTypes);

            // run the query
            var list = new List<WorkItemNode>();
            if (queryDef.QueryType == QueryType.List)
            {
                foreach (WorkItem wi in query.RunQuery())
                {
                    list.Add(new WorkItemNode() { WorkItem = wi, RelationshipToParent = "" });
                }
            }
            else
            {
                var workItemLinks = query.RunLinkQuery().ToList();
                list = WalkLinks(workItemLinks, linkTypes, null);
            }

            return list;
        }

        private void cbTestSteps_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbTestSteps.Checked)
                flag3 = 1;
            else
                flag3 = 0;
        }

        private void writeTestSteps(ref Excel.Worksheet xlWorkSheet, ITestStep tStep, ref int iRow, ref int iColumn)
        {
            string strStep = Regex.Replace(tStep.Title, @"<[^>]+>|&nbsp;", "").Trim();
            string strExpectedResult = Regex.Replace(tStep.ExpectedResult, @"<[^>]+>|&nbsp;", "").Trim();

            //     iColumn = 2;
            iRow++;
            xlWorkSheet.Cells[iRow, 19] = strStep;
            xlWorkSheet.Cells[iRow, 20] = strExpectedResult;
            xlWorkSheet.Cells[iRow, 15] = "Test Step";

        }
        private List<WorkItemNode> WalkLinks(List<WorkItemLinkInfo> workItemLinks, List<WorkItemLinkType> linkTypes, WorkItemNode current)
        {
            var currentId = 0;
            if (current != null)
            {
                currentId = current.WorkItem.Id;
            }

            var workItems = (from linkInfo in workItemLinks
                             where linkInfo.SourceId == currentId
                             select new WorkItemNode()
                             {
                                 WorkItem = _teamWorkItemStore.GetWorkItem(linkInfo.TargetId),
                                    RelationshipToParent = linkInfo.LinkTypeId == 0 ? "Parent" :
                                    linkTypes.Single(lt => lt.ForwardEnd.Id == linkInfo.LinkTypeId).ForwardEnd.Name
                             }).ToList();
            workItems.ForEach(w => w.Children = WalkLinks(workItemLinks, linkTypes, w));

            return workItems;
        }

        private void GenerateReport(ref Excel.Worksheet xlWorkSheet, ref String upperBound, ref String lowerBound, List<WorkItemNode> workItemNodes, IEnumerable<ITestRun> testRuns, ref ITestCaseResultHelper allTestCaseResults, ref ITestCaseHelper allTestCases, ref int row, ref int col)
        {
            ResultCounter usResultCounter;
            foreach (WorkItemNode workItem in workItemNodes)
            {
                xlWorkSheet.Cells[row, 14] = workItem.WorkItem.Id.ToString();
                xlWorkSheet.Cells[row, 15] = workItem.WorkItem.Fields["Work Item Type"].OriginalValue.ToString();
                xlWorkSheet.Cells[row, 16] = workItem.WorkItem.State.ToString();
                xlWorkSheet.Cells[row, 17] = workItem.WorkItem.Fields["Priority"].OriginalValue.ToString();
                xlWorkSheet.Cells[row, 18] = workItem.WorkItem.Title.ToString();
                if (flag3 == 1)
                {
                    xlWorkSheet.Cells[row, 22] = workItem.WorkItem.Tags.ToString();
                    xlWorkSheet.Cells[row, 23] = workItem.WorkItem.AreaPath.ToString();
                    xlWorkSheet.Cells[row, 24] = workItem.WorkItem.IterationPath.ToString();
                    xlWorkSheet.Cells[row, 25] = workItem.WorkItem.NodeName.ToString();
                }
                else
                {
                    xlWorkSheet.Cells[row, 20] = workItem.WorkItem.Tags.ToString();
                    xlWorkSheet.Cells[row, 21] = workItem.WorkItem.AreaPath.ToString();
                    xlWorkSheet.Cells[row, 22] = workItem.WorkItem.IterationPath.ToString();
                    xlWorkSheet.Cells[row, 23] = workItem.WorkItem.NodeName.ToString();
                }

                int iUSRowCount = row;
                upperBound += row;
                row++;

                usResultCounter = new ResultCounter();

                GetTestCases(ref xlWorkSheet, ref upperBound, ref lowerBound, workItem, testRuns, ref allTestCaseResults, ref allTestCases, ref row, ref col, ref usResultCounter);

                float passPercent = ((usResultCounter.PassCount / usResultCounter.ExecutedCount) * 100);
                float failPercent = ((usResultCounter.FailCount / usResultCounter.ExecutedCount) * 100);

                xlWorkSheet.Cells[iUSRowCount, 1] = usResultCounter.CreatedCount;
                xlWorkSheet.Cells[iUSRowCount, 2] = usResultCounter.ExecutedCount;
                xlWorkSheet.Cells[iUSRowCount, 3] = usResultCounter.ActiveCount;
                xlWorkSheet.Cells[iUSRowCount, 4] = usResultCounter.PassCount;
                xlWorkSheet.Cells[iUSRowCount, 5] = usResultCounter.FailCount;
                xlWorkSheet.Cells[iUSRowCount, 6] = usResultCounter.BlockedCount;
                xlWorkSheet.Cells[iUSRowCount, 7] = usResultCounter.NACount;
                xlWorkSheet.Cells[iUSRowCount, 8] = usResultCounter.OtherCount;
                xlWorkSheet.Cells[iUSRowCount, 9] = passPercent.ToString("00.00");
                xlWorkSheet.Cells[iUSRowCount, 10] = failPercent.ToString("00.00");
            }
        }

        private void GetTestCases(ref Excel.Worksheet xlWorkSheet, ref String upperBound, ref String lowerBound, WorkItemNode workItemNode, IEnumerable<ITestRun> testRuns, ref ITestCaseResultHelper allTestCaseResults, ref ITestCaseHelper allTestCases, ref int row, ref int col, ref ResultCounter usResultCounter)
        {
            foreach (WorkItemNode workItem in workItemNode.Children)
            {
                int iTCTitleRow = row;

                xlWorkSheet.Cells[row, 14] = workItem.WorkItem.Id.ToString();
                xlWorkSheet.Cells[row, 15] = workItem.WorkItem.Fields["Work Item Type"].OriginalValue.ToString();
                xlWorkSheet.Cells[row, 16] = workItem.WorkItem.State.ToString();
                xlWorkSheet.Cells[row, 17] = workItem.WorkItem.Fields["Priority"].OriginalValue.ToString();
                xlWorkSheet.Cells[row, 18] = workItem.WorkItem.Title.ToString();
                if (flag3 == 1)
                {
                    xlWorkSheet.Cells[row, 21] = workItem.WorkItem.Fields["Complexity"].OriginalValue.ToString();
                    xlWorkSheet.Cells[row, 22] = workItem.WorkItem.Tags.ToString();
                    xlWorkSheet.Cells[row, 23] = workItem.WorkItem.AreaPath.ToString();
                    xlWorkSheet.Cells[row, 24] = workItem.WorkItem.IterationPath.ToString();
                    xlWorkSheet.Cells[row, 25] = workItem.WorkItem.NodeName.ToString();

                    TestActionCollection testActions = allTestCases.Find(workItem.WorkItem.Id).Actions;
                    foreach (ITestAction testAction in testActions)
                    {
                        var tstSharedStepRef = testAction as ISharedStepReference;
                        string strStep = string.Empty;
                        string strExpectedResult = string.Empty;

                        if (tstSharedStepRef != null)
                        {
                            ISharedStep tstSharedStep = tstSharedStepRef.FindSharedStep();
                            foreach (ITestAction tstSharedAction in tstSharedStep.Actions)
                            {
                                ITestStep tstSharedTestStep = tstSharedAction as ITestStep;
                                writeTestSteps(ref xlWorkSheet, tstSharedTestStep, ref row, ref col);
                            }
                        }
                        else {
                            ITestStep tstSharedTestStep = testAction as ITestStep;
                            writeTestSteps(ref xlWorkSheet, tstSharedTestStep, ref row, ref col);
                        }
                    }
                    lowerBound += (row - 1);
                }
                else
                {
                    xlWorkSheet.Cells[row, 19] = workItem.WorkItem.Fields["Complexity"].OriginalValue.ToString();
                    xlWorkSheet.Cells[row, 20] = workItem.WorkItem.Tags.ToString();
                    xlWorkSheet.Cells[row, 21] = workItem.WorkItem.AreaPath.ToString();
                    xlWorkSheet.Cells[row, 22] = workItem.WorkItem.IterationPath.ToString();
                    xlWorkSheet.Cells[row, 23] = workItem.WorkItem.NodeName.ToString();
                }
                // Get the test results
                //var testCaseResult = allTestCaseResults.ByTestId(testCase.Id).Where(b => b.Outcome == TestOutcome.Passed || b.Outcome == TestOutcome.Failed);
                // Added for WIC project
                var testCaseResult = allTestCaseResults.ByTestId(workItem.WorkItem.Id).Where(b => b.Outcome == TestOutcome.Passed || b.Outcome == TestOutcome.Failed || b.Outcome == TestOutcome.NotApplicable || b.Outcome == TestOutcome.Blocked);

                // apply date filter to the results
                if (cbApplyDateFilter.Checked)
                {
                    testCaseResult = testCaseResult.Where(t => DateTime.Compare(t.DateCompleted.Date, dtpCompleteStart.Value.Date) >= 0 && DateTime.Compare(t.DateCompleted.Date, dtpCompleteEnd.Value.Date) <= 0);
                }

                // apply Run Type filter
                if (string.Compare(cmbRunType.Text.Trim(), "All") != 0)
                {
                    testCaseResult = testCaseResult.Where(a => testRuns.FirstOrDefault(b => b.Id == a.TestRunId) != null);
                }

                // order the output in decending order to get the latest record
                testCaseResult = testCaseResult.OrderByDescending(t => t.DateCompleted);

                if (testCaseResult.Count() > 0)
                {
                    int runCount = testCaseResult.Count();
                    float passCount = testCaseResult.Where(p => p.Outcome == TestOutcome.Passed).Count();
                    float failCount = testCaseResult.Where(p => p.Outcome == TestOutcome.Failed).Count();
                    float naCount = testCaseResult.Where(p => p.Outcome == TestOutcome.NotApplicable).Count();
                    float blockedCount = testCaseResult.Where(p => p.Outcome == TestOutcome.Blocked).Count();

                    float passPercent = ((passCount / runCount) * 100);
                    float failPercent = ((failCount / runCount) * 100);

                    xlWorkSheet.Cells[iTCTitleRow, 4] = passCount;
                    xlWorkSheet.Cells[iTCTitleRow, 5] = failCount;
                    xlWorkSheet.Cells[iTCTitleRow, 6] = blockedCount;
                    xlWorkSheet.Cells[iTCTitleRow, 7] = naCount;
                    xlWorkSheet.Cells[iTCTitleRow, 9] = passPercent.ToString("00.00");
                    xlWorkSheet.Cells[iTCTitleRow, 10] = failPercent.ToString("00.00");
                    xlWorkSheet.Cells[iTCTitleRow, 11] = runCount;
                    xlWorkSheet.Cells[iTCTitleRow, 12] = testCaseResult.FirstOrDefault().Outcome.ToString();
                    xlWorkSheet.Cells[iTCTitleRow, 13] = testCaseResult.FirstOrDefault().DateCompleted.ToString();

                    switch (testCaseResult.FirstOrDefault().Outcome.ToString())
                    {
                        case "Active":
                            usResultCounter.ActiveCount += 1;
                            break;
                        case "Passed":
                            usResultCounter.PassCount += 1;
                            break;
                        case "Failed":
                            usResultCounter.FailCount += 1;
                            break;
                        case "NotApplicable":
                            usResultCounter.NACount += 1;
                            break;
                        case "Blocked":
                            usResultCounter.BlockedCount += 1;
                            break;
                        default:
                            usResultCounter.OtherCount += 1;
                            break;
                    }
                }
                else
                {
                    xlWorkSheet.Cells[iTCTitleRow, 12] = "Not Run";
                }

                upperBound += row;
                row++;
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            DateTime startDateTime = DateTime.Now;

            if (!string.IsNullOrEmpty(txtTFSQuery.Text))
            {
                flag2 = 1;
            }
            if (!string.IsNullOrEmpty(txtFileName.Text))
            {
                flag5 = 1;
            }
            if (!string.IsNullOrEmpty(txtSaveFolder.Text))
            {
                flag4 = 1;
            }
            if (cbApplyDateFilter.Checked && (DateTime.Compare(dtpCompleteEnd.Value, dtpCompleteStart.Value) >= 0))
            {
                flag6 = 1;
            }
            else if (!cbApplyDateFilter.Checked)
            {
                flag6 = 1;
            }
            else
            {
                flag6 = 0;
            }

            if (flag1 == 1 && flag2 == 1 && flag4 == 1 && flag5 == 1 && flag6 == 1)
            {
                List<WorkItemNode> workItemNodes = GetWorkItems(tfsQueryRootFolder, txtTFSQuery.Text.Trim());

                if (workItemNodes != null)
                {

                    this.Cursor = Cursors.WaitCursor;
                    btnExport.Enabled = false;
                    btnCancel.Enabled = false;
                    btnTeamProject.Enabled = false;
                    btnFolderBrowse.Enabled = false;
                    string filePath = string.Format(@"{0}\{1}.xlsx", txtSaveFolder.Text.Trim(), txtFileName.Text.Trim());

                    Excel.Application xlApp;
                    Excel.Workbook xlWorkBook;
                    Excel.Worksheet xlWorkSheet;
                    object misValue = System.Reflection.Missing.Value;
                    Excel.Range chartRange;

                    xlApp = new Excel.Application();
                    xlWorkBook = null;

                    if (!File.Exists(filePath))
                    {
                        xlWorkBook = xlApp.Workbooks.Add(misValue);
                        xlWorkBook.SaveAs(filePath);
                    }

                    xlWorkBook = xlApp.Workbooks.Open(filePath);
                    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Add();
                    xlWorkSheet.Name = string.Concat(xlWorkSheet.Name.Substring(5), string.Format(". {0} - {1}", "TestCases", cmbRunType.Text));

                    xlWorkSheet.Cells[1, 1] = "Created";
                    xlWorkSheet.Cells[1, 2] = "Executed";
                    xlWorkSheet.Cells[1, 3] = "Active";
                    xlWorkSheet.Cells[1, 4] = "Pass";
                    xlWorkSheet.Cells[1, 5] = "Fail";
                    xlWorkSheet.Cells[1, 6] = "Blocked";
                    xlWorkSheet.Cells[1, 7] = "NA";
                    xlWorkSheet.Cells[1, 8] = "Other";
                    xlWorkSheet.Cells[1, 9] = "Pass %";
                    xlWorkSheet.Cells[1, 10] = "Fail %";
                    xlWorkSheet.Cells[1, 11] = "# of Runs";
                    xlWorkSheet.Cells[1, 12] = "Latest Result";
                    xlWorkSheet.Cells[1, 13] = "Last Run Date";
                    xlWorkSheet.Cells[1, 14] = "ID";
                    xlWorkSheet.Cells[1, 15] = "WI Type";
                    xlWorkSheet.Cells[1, 16] = "State";
                    xlWorkSheet.Cells[1, 17] = "Priority";
                    xlWorkSheet.Cells[1, 18] = "Title";

                    if (flag3 == 1)
                    {
                        xlWorkSheet.Cells[1, 19] = "Actions";
                        xlWorkSheet.Cells[1, 20] = "Expected Output";
                        xlWorkSheet.Cells[1, 21] = "Complexity";
                        xlWorkSheet.Cells[1, 22] = "Tags";
                        xlWorkSheet.Cells[1, 23] = "Area Path";
                        xlWorkSheet.Cells[1, 24] = "Iteration Path";
                        xlWorkSheet.Cells[1, 25] = "Module/Feature";

                        (xlWorkSheet.Columns["S", Type.Missing]).ColumnWidth = 40;
                        (xlWorkSheet.Columns["T", Type.Missing]).ColumnWidth = 40;
                        (xlWorkSheet.Columns["U", Type.Missing]).ColumnWidth = 12;
                        (xlWorkSheet.Columns["V", Type.Missing]).ColumnWidth = 30;
                        (xlWorkSheet.Columns["W", Type.Missing]).ColumnWidth = 40;
                        (xlWorkSheet.Columns["X", Type.Missing]).ColumnWidth = 40;
                        (xlWorkSheet.Columns["Y", Type.Missing]).ColumnWidth = 30;
                    }
                    else
                    {
                        xlWorkSheet.Cells[1, 19] = "Complexity";
                        xlWorkSheet.Cells[1, 20] = "Tags";
                        xlWorkSheet.Cells[1, 21] = "Area Path";
                        xlWorkSheet.Cells[1, 22] = "Iteration Path";
                        xlWorkSheet.Cells[1, 23] = "Module/Feature";

                        (xlWorkSheet.Columns["S", Type.Missing]).ColumnWidth = 12;
                        (xlWorkSheet.Columns["T", Type.Missing]).ColumnWidth = 30;
                        (xlWorkSheet.Columns["U", Type.Missing]).ColumnWidth = 40;
                        (xlWorkSheet.Columns["V", Type.Missing]).ColumnWidth = 40;
                        (xlWorkSheet.Columns["W", Type.Missing]).ColumnWidth = 30;
                    }

                    (xlWorkSheet.Columns["A", Type.Missing]).ColumnWidth = 7;
                    (xlWorkSheet.Columns["B", Type.Missing]).ColumnWidth = 7;
                    (xlWorkSheet.Columns["C", Type.Missing]).ColumnWidth = 5;
                    (xlWorkSheet.Columns["D", Type.Missing]).ColumnWidth = 5;
                    (xlWorkSheet.Columns["E", Type.Missing]).ColumnWidth = 5;
                    (xlWorkSheet.Columns["F", Type.Missing]).ColumnWidth = 7;
                    (xlWorkSheet.Columns["G", Type.Missing]).ColumnWidth = 5;
                    (xlWorkSheet.Columns["H", Type.Missing]).ColumnWidth = 5;
                    (xlWorkSheet.Columns["I", Type.Missing]).ColumnWidth = 5;
                    (xlWorkSheet.Columns["J", Type.Missing]).ColumnWidth = 5;
                    (xlWorkSheet.Columns["K", Type.Missing]).ColumnWidth = 8;
                    (xlWorkSheet.Columns["L", Type.Missing]).ColumnWidth = 12;
                    (xlWorkSheet.Columns["M", Type.Missing]).ColumnWidth = 12;
                    (xlWorkSheet.Columns["N", Type.Missing]).ColumnWidth = 5;
                    (xlWorkSheet.Columns["O", Type.Missing]).ColumnWidth = 8;
                    (xlWorkSheet.Columns["P", Type.Missing]).ColumnWidth = 8;
                    (xlWorkSheet.Columns["Q", Type.Missing]).ColumnWidth = 8;
                    (xlWorkSheet.Columns["R", Type.Missing]).ColumnWidth = 40;

                    int row = 2;
                    int col = 1;
                    string upperBound = "a";
                    string lowerBound = "a";

                    // cache tfs query results
                    ITestRunHelper allTestRuns = null;
                    IEnumerable<ITestRun> testRuns = null;
                    ITestCaseResultHelper allTestCaseResults = null;
                    ITestCaseHelper allTestCases = null;

                    try
                    {
                        //Cache the testRuns
                        allTestRuns = _teamProject.TestRuns;

                        if (string.Compare(cmbRunType.Text.Trim(), "Manual") == 0)
                        {
                            testRuns = allTestRuns.Query("select TestRunID From TestRun where IsAutomated=0");
                        }
                        else if (string.Compare(cmbRunType.Text.Trim(), "Automated") == 0)
                        {
                            testRuns = allTestRuns.Query("select TestRunID From TestRun where IsAutomated=1");
                        }

                        //Cache testresults
                        allTestCaseResults = this._teamProject.TestResults;
                        allTestCases = this._teamProject.TestCases;

                        ///ExportTestcases(ref xlWorkSheet, ref upperBound, ref lowerBound, ref testCases, testRuns, ref allTestCaseResults, ref row, ref col);
                        GenerateReport(ref xlWorkSheet, ref upperBound, ref lowerBound, workItemNodes, testRuns, ref allTestCaseResults, ref allTestCases, ref row, ref col);

                        lowerBound = "y";
                        lowerBound += (row - 1);
                        chartRange = xlWorkSheet.get_Range("a1", "y1");
                        chartRange.Font.Bold = true;
                        chartRange.Interior.Color = 18018018;
                        xlWorkSheet.UsedRange.Replace("&gt;", ">");
                        xlWorkSheet.UsedRange.Font.Size = 9;
                        xlWorkSheet.UsedRange.WrapText = true;

                        TimeSpan timeTaken = startDateTime - DateTime.Now;
                        //MessageBox.Show(string.Format("Test Cases exported successfully to specified filepath. Total Time Taken: {0}", timeTaken.ToString()), "Success", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        MessageBox.Show(string.Format("Completed and the results are saved at: {0}", filePath));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    finally
                    {
                        xlWorkBook.Save();
                        xlWorkBook.Close(true, misValue, misValue);
                        xlApp.Quit();

                        releaseObject(xlApp);
                        releaseObject(xlWorkBook);
                        releaseObject(xlWorkSheet);
                        this.Cursor = Cursors.Arrow;

                        btnExport.Enabled = true;
                        btnCancel.Enabled = true;
                        btnTeamProject.Enabled = true;
                        btnFolderBrowse.Enabled = true;

                    }
                }
                else
                {
                    MessageBox.Show("All fields are not populated.", "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                MessageBox.Show(string.Format("{0} returned zero workitems", txtTFSQuery.Text));
            }
        }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}